/*
 * types.tree.js
 *
 * Copyright (C) 2012 - OS3 srl - http://www.os3.it
 *
 * Written by: Fabio Rotondo - fabio.rotondo@os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * version 2 of the License ONLY.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * NOTE: this is the GPL version of the library. If you want to include this 
 *       library inside a CLOSED SOURCE / PROPRIETARY software, you need 
 *       to purchase a COMMERCIAL LICENSE. See http://www.os3.it/license/
 *       for more info.
 */

if ( typeof ( exports ) !== 'undefined' )
{
	var liwe = require ( "./liwe" );
	liwe.types = require ( "./types" );
}

liwe.types._tree_node = function ( val, parent )
{
	this.value = val;
	this.parent = parent;
	
	val._tree_node = this;

	this.nodes = null;
};

liwe.types._tree_node.prototype.add = function ( val )
{
	if ( ! this.nodes ) this.nodes = list ();

	var n = new liwe.types._tree_node ( val, this );

	this.nodes.push ( n );

	return n;
};

liwe.types._tree_node.prototype.traverse = function ( cback )
{
	if ( ! cback ) return;

	cback ( this.value );

	function _trav ( n )
	{
		n.traverse ( cback );
	}

	if ( this.nodes && this.nodes.length ) 
		this.nodes.iterate ( _trav );
};

liwe.types._tree_node.prototype.depth_first = function ( cback )
{
	if ( ! cback ) return;

	function _depth ( n ) { n.depth_first ( cback ); };

	if ( this.nodes && this.nodes.length ) this.nodes.iterate ( _depth );

	cback ( this.value );
};

liwe.types._tree_node.prototype.breadth_first = function ( cback )
{
	if ( ! cback ) return;

	function _node ( n ) { n.breadth_first ( cback ); };

	if ( ! this.parent ) cback ( this.value );

	if ( this.nodes && this.nodes.length ) 
	{
		this.nodes.iterate ( function ( n ) { cback ( n.value ); } );
		this.nodes.iterate ( _node );
	}

};

liwe.types.tree = function ()
{
	this.root = new liwe.types._tree_node ( "(root)", null );

	return this.root;
};

var tree = liwe.types.tree;

if ( typeof ( exports ) !== 'undefined' )
	module.exports = function () { return new liwe.types.tree (); };
